//
//  ZJNavigationController.m
//  Copyright © 2016年 babbage. All rights reserved.
//

#import "ZJNavigationController.h"

@interface ZJNavigationController ()<UIGestureRecognizerDelegate,UINavigationControllerDelegate>
@property(nonatomic,weak) UIViewController* currentShowVC;
@end

@implementation ZJNavigationController

-(void)viewDidLoad{
    [super viewDidLoad];
}

-(void)pushViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (self.viewControllers.count > 0) {
        viewController.hidesBottomBarWhenPushed = YES;
        UIButton * backButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [backButton setBackgroundImage:[UIImage imageNamed:@"back"] forState:(UIControlStateNormal)];
        [backButton setBackgroundImage:[UIImage imageNamed:@"back"] forState:(UIControlStateHighlighted)];
        backButton.frame = CGRectMake(0, 0, 12, 22);
        [backButton addTarget:self action:@selector(back) forControlEvents:(UIControlEventTouchUpInside)];
        viewController.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backButton];
       
    }
   
    
    [super pushViewController:viewController animated:animated];
}

-(void)back{
    [self popViewControllerAnimated:YES];
}

-(id)initWithRootViewController:(UIViewController *)rootViewController
{
    ZJNavigationController* nvc = [super initWithRootViewController:rootViewController];
    self.interactivePopGestureRecognizer.delegate = self;
    nvc.delegate = self;
    return nvc;
}
-(void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
}
-(void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated{
    if (navigationController.viewControllers.count == 1)
        self.currentShowVC = Nil;
    else
        self.currentShowVC = viewController;
}
-(BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if (gestureRecognizer == self.interactivePopGestureRecognizer) {
        return (self.currentShowVC == self.topViewController); //the most important
    }
    return YES;
}

-(BOOL)gestureRecognizerShouldBegin{
    [self popToRootViewControllerAnimated:YES];
    return YES;
}

@end
